package com.quanyan.activity.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.quanyan.activity.entity.ActivityDesc;
import com.quanyan.activity.entity.ActivityInfo;
import com.quanyan.activity.entity.ActivityMedia;
import com.quanyan.activity.entity.db.*;
import com.quanyan.activity.mapper.*;
import com.quanyan.activity.request.ReqGroupVo;
import com.quanyan.activity.response.GroupData;
import com.quanyan.activity.response.GroupInfo;
import com.quanyan.activity.response.RespGroupInfo;
import com.quanyan.activity.service.ActivityOpenService;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.comment.reqeust.APIRequest;
import com.quanyan.comment.reqeust.ReqUserCollect;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.BeanCopierUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.utils.Limit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service("activityOpenService")
public class ActivityOpenServiceImpl
        implements ActivityOpenService
{
    private static final Logger logger = LoggerFactory.getLogger(ActivityOpenServiceImpl.class);
    @Value("${group.IM.service.url}")
    private String groupIMServiceUrl;
    @Autowired
    private TbActivityMapper activityMapper;
    @Autowired
    private TbActivityMultimediaMapper tbActivityMultimediaMapper;
    @Autowired
    private TbActivityDescMapper tbActivityDescMapper;
    @Autowired
    private QueryMyActivityMapper queryMyActivityMapper;
    @Autowired
    private ActivityMultimediaMapper activityMultimediaMapper;
    @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
    public ActivityInfo saveActivity(ActivityInfo activityInfo)
    {
        TbActivity tbActivity = new TbActivity();
        copyReqToActivity(activityInfo, tbActivity);
        List<ActivityMedia> activityMediaList = activityInfo.getActivityMediaList();
        RespGroupInfo group = createGroup(activityInfo);
        if (null != group)
        {
            GroupData groupData = group.getData();
            if (null != groupData)
            {
                List<GroupInfo> groupInfos = groupData.getGroupinfo();
                if (CollectionUtils.isNotEmpty(groupInfos)) {
                    tbActivity.setGroupId(((GroupInfo)groupInfos.get(0)).getGroupid());
                }
            }
        }
        Integer.valueOf(this.activityMapper.insertSelective(tbActivity));
        insertActivityDesc(activityInfo, tbActivity.getId());
        TbActivityMultimedia tbActivityMultimedia = null;
        if (CollectionUtils.isNotEmpty(activityMediaList)) {
            for (ActivityMedia activityMedia : activityMediaList)
            {
                tbActivityMultimedia = new TbActivityMultimedia();
                insertMedia(tbActivity.getId(), tbActivityMultimedia, activityMedia);
                tbActivityMultimedia.setId(tbActivityMultimedia.getId());
            }
        }
        activityInfo.setId(tbActivity.getId());
        return activityInfo;
    }

    private RespGroupInfo createGroup(ActivityInfo activityInfo)
    {
        ReqGroupVo reqGroupVo = new ReqGroupVo();
        reqGroupVo.setVer("1.0");
        reqGroupVo.setExtid(activityInfo.getId());
        reqGroupVo.setProtocol_ver(Integer.valueOf(1));
        reqGroupVo.setCurrentUid(activityInfo.getUid());
        reqGroupVo.setApproval(Byte.valueOf((byte)0));
        reqGroupVo.setGroupdescriptions(activityInfo.getName());
        reqGroupVo.setGroupname(activityInfo.getName());
        if (null != activityInfo.getRespActivityPoster()) {
            reqGroupVo.setHead(activityInfo.getRespActivityPoster().getUrl());
        }
        reqGroupVo.setIspublic(Byte.valueOf((byte)0));
        reqGroupVo.setType(Byte.valueOf((byte)3));
        reqGroupVo.setMaxusers(500);
        reqGroupVo.setOwner(activityInfo.getUid());
        RespGroupInfo respGroupVo = new RespGroupInfo();
        try
        {
            String postJson = JSON.toJSONString(reqGroupVo);
            logger.warn("调用C端接口传参：groupIMServiceUrl:" + this.groupIMServiceUrl + "  postJson:" + postJson);
            String result = HttpClientUtils.postJson(this.groupIMServiceUrl, postJson);
            logger.warn("调用C端接口返回json字符串：result:" + result);
            Gson gson = new Gson();
            respGroupVo = (RespGroupInfo)gson.fromJson(result, RespGroupInfo.class);
        }
        catch (Exception e)
        {
            logger.error("创建活动聊天群组失败，原因:{}", e);
        }
        return respGroupVo;
    }

    public void insertActivityDesc(ActivityInfo activityInfo, Integer activityId)
    {
        ActivityDesc activityDesc = activityInfo.getActivityDesc();
        TbActivityDesc tbActivityDesc = new TbActivityDesc();
        if (null != activityDesc)
        {
            tbActivityDesc.setAttentionDesc(activityDesc.getAttentionDesc());
            tbActivityDesc.setBodyDesc(activityDesc.getBodyDesc());
            tbActivityDesc.setActivityId(activityId);
            this.tbActivityDescMapper.insertSelective(tbActivityDesc);
        }
    }

    @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
    public ActivityInfo updateTbActivity(ActivityInfo activityInfo)
    {
        try
        {
            TbActivity tbActivity = new TbActivity();
            copyReqToActivity(activityInfo, tbActivity);
            logger.warn("更新参数："+JSON.toJSONString(tbActivity));
            this.activityMapper.updateByPrimaryKeySelective(tbActivity);
            activityInfo.setId(tbActivity.getId());
            logger.warn("==========更新成功=============");
        }
        catch (Exception e)
        {
            logger.warn(e.getMessage());
            throw new BizException("更新失败");
        }
        return activityInfo;
    }

    @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
    public ActivityInfo updateActivity(ActivityInfo activityInfo)
    {
        TbActivity tbActivity = new TbActivity();
        copyReqToActivity(activityInfo, tbActivity);
        List<ActivityMedia> activityMediaList = activityInfo.getActivityMediaList();
        this.activityMapper.updateByPrimaryKeySelective(tbActivity);
        Integer activityId = tbActivity.getId();
        updatActivityDesc(activityInfo, activityId);
        if (CollectionUtils.isNotEmpty(activityMediaList))
        {
            TbActivityMultimediaExample example = new TbActivityMultimediaExample();
            TbActivityMultimediaExample.Criteria criteria = example.createCriteria();
            criteria.andActivityIdEqualTo(activityId);
            criteria.andIsDeleteEqualTo(Byte.valueOf((byte)0));
            List<Integer> idList = new ArrayList();
            List<TbActivityMultimedia> list = this.tbActivityMultimediaMapper.selectByExample(example);
            if ((null != list) && (list.size() > 0))
            {
                for (TbActivityMultimedia willDelete : list) {
                    idList.add(willDelete.getId());
                }
                Map<String, Object> map = new HashMap();
                map.put("idList", idList);
                map.put("isDelete", Integer.valueOf(1));
                this.activityMultimediaMapper.batchUpdateDelete(map);
            }
            List<TbActivityMultimedia> newList = new ArrayList();
            for (ActivityMedia activityMedia : activityMediaList)
            {
                TbActivityMultimedia tbActivityMultimedia = new TbActivityMultimedia();
                tbActivityMultimedia.setStatus(Byte.valueOf((byte)0));
                tbActivityMultimedia.setActivityId(activityId);
                tbActivityMultimedia.setIsMain(Byte.valueOf((byte)0));
                tbActivityMultimedia.setMultimediaUrl(activityMedia.getImageUrl());
                tbActivityMultimedia.setType(Byte.valueOf((byte)0));
                newList.add(tbActivityMultimedia);
            }
            this.activityMultimediaMapper.batchInsert(newList);
        }
        activityInfo.setId(activityId);
        return activityInfo;
    }

    public void updatActivityDesc(ActivityInfo activityInfo, Integer activityId)
    {
        TbActivityDescExample example = new TbActivityDescExample();
        TbActivityDescExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        List<TbActivityDesc> list = this.tbActivityDescMapper.selectByExample(example);
        ActivityDesc activityDesc = activityInfo.getActivityDesc();
        TbActivityDesc tbActivityDesc = null;
        if ((null != list) && (list.size() == 1)) {
            tbActivityDesc = (TbActivityDesc)list.get(0);
        }
        if (null != activityDesc)
        {
            tbActivityDesc.setAttentionDesc(activityDesc.getAttentionDesc());
            tbActivityDesc.setBodyDesc(activityDesc.getBodyDesc());
            this.tbActivityDescMapper.updateByPrimaryKey(tbActivityDesc);
        }
    }

    public Integer insertMedia(Integer activityId, TbActivityMultimedia tbActivityMultimedia, ActivityMedia activityMedia)
    {
        tbActivityMultimedia.setStatus(Byte.valueOf((byte)0));
        tbActivityMultimedia.setActivityId(activityId);
        tbActivityMultimedia.setIsMain(Byte.valueOf(activityMedia.getIsMain() == null ? 0 : activityMedia.getIsMain().byteValue()));
        tbActivityMultimedia.setMultimediaUrl(activityMedia.getImageUrl());
        tbActivityMultimedia.setType(Byte.valueOf((byte)0));
        return Integer.valueOf(this.tbActivityMultimediaMapper.insertSelective(tbActivityMultimedia));
    }

    private void copyReqToActivity(ActivityInfo reqActivity, TbActivity tbActivity)
    {
        if (null != reqActivity)
        {
            tbActivity.setId(reqActivity.getId());
            if (null != reqActivity.getRespActivityPoster()) {
                tbActivity.setPosterPicId(reqActivity.getRespActivityPoster().getId());
            }
            tbActivity.setAlreadySignTotalNum(reqActivity.getAlreadySignTotalNum());
            tbActivity.setSignStartTime(reqActivity.getSignStartTime());
            tbActivity.setSignEndTime(reqActivity.getSignEndTime());
            tbActivity.setLimitNum(reqActivity.getLimitNum());
            tbActivity.setCategoryId(reqActivity.getCategoryId());
            tbActivity.setStartTime(reqActivity.getStartTime());
            tbActivity.setEndTime(reqActivity.getEndTime());
            tbActivity.setExtendName(reqActivity.getExtendName());
            tbActivity.setIsOfficial(reqActivity.getIsOfficial());
            tbActivity.setName(reqActivity.getName());
            tbActivity.setPrice(reqActivity.getPrice());
            if (null != reqActivity.getPlaceId()) {
                tbActivity.setPlaceId(reqActivity.getPlaceId());
            }
            if (null != reqActivity.getPlaceId()) {
                tbActivity.setPlaceUnitId(reqActivity.getPlaceUnitId());
            }
            tbActivity.setStatus(reqActivity.getStatus());
            if ((null != reqActivity.getPlaceAddress()) && (!"".equals(reqActivity.getPlaceAddress()))) {
                tbActivity.setPlaceAddress(reqActivity.getPlaceAddress());
            }
        }
    }

    public int cancelActivityById(Integer activityId)
    {
        TbActivity tbActivity = this.activityMapper.selectByPrimaryKey(activityId);
        if (null != tbActivity)
        {
            tbActivity.setStatus(Constants.BYTE_TWO);
            int id = this.activityMapper.updateByPrimaryKeySelective(tbActivity);
            return id;
        }
        return 0;
    }

    /**
     * 活动简要
     * @param activityId
     * @return
     */
    public ActivityInfo selectOneActivityById(Integer activityId)
    {
        TbActivity tbActivity = this.activityMapper.selectByPrimaryKey(activityId);
        if (null == tbActivity) {
            return null;
        }
        ActivityInfo activityInfo = new ActivityInfo();
        BeanCopierUtils.copyProperties(tbActivity, activityInfo);
        activityInfo.setPosterPicId(tbActivity.getPosterPicId());
        activityInfo.setPlaceAddress(tbActivity.getPlaceAddress());
        activityInfo.setStartTime(tbActivity.getStartTime());
        activityInfo.setGroupId(tbActivity.getGroupId());
        ActivityDesc activityDesc = getActivityDesc(activityId);
        if(null == activityDesc)
        {
            logger.warn("不完整数据，活动ID：" + tbActivity.getId());
        }
        activityInfo.setActivityDesc(activityDesc);
        return activityInfo;
    }

    public ActivityInfo queryOneActivityById(Integer activityId)
    {
        TbActivity tbActivity = this.activityMapper.selectByPrimaryKey(activityId);
        if (null == tbActivity) {
            return null;
        }
        ActivityDesc activityDesc = getActivityDesc(activityId);

        List<TbActivityMultimedia> tbActivityMultimediaList = getTbActivityMultimediaList(activityId);
        ActivityInfo activityInfo = new ActivityInfo();
        BeanCopierUtils.copyProperties(tbActivity, activityInfo);

        List<ActivityMedia> respActivityMediaList = new ArrayList();
        for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimediaList)
        {
            ActivityMedia activityMedia = new ActivityMedia();
            activityMedia.setImageUrl(tbActivityMultimedia.getMultimediaUrl());
            activityMedia.setState(Integer.valueOf(tbActivityMultimedia.getStatus().intValue()));
            activityMedia.setIsMain(Integer.valueOf(tbActivityMultimedia.getIsMain().intValue()));
            activityMedia.setId(tbActivityMultimedia.getId());
            respActivityMediaList.add(activityMedia);
        }
        activityInfo.setPosterPicId(tbActivity.getPosterPicId());
        activityInfo.setPlaceAddress(tbActivity.getPlaceAddress());
        activityInfo.setActivityMediaList(respActivityMediaList);
        activityInfo.setActivityDesc(activityDesc);
        activityInfo.setStartTime(tbActivity.getStartTime());
        if(null == activityInfo.getGroupId() || "".equals(activityInfo.getGroupId()))
        {
            RespGroupInfo group = createGroup(activityInfo);
            if (null != group)
            {
                GroupData groupData = group.getData();
                if (null != groupData)
                {
                    List<GroupInfo> groupInfos = groupData.getGroupinfo();
                    if (CollectionUtils.isNotEmpty(groupInfos)) {
                        activityInfo.setGroupId(((GroupInfo)groupInfos.get(0)).getGroupid());
                    }
                }
            }
        }
        return activityInfo;
    }

    public List<TbActivityMultimedia> getTbActivityMultimediaList(Integer activityId)
    {
        TbActivityMultimediaExample example = new TbActivityMultimediaExample();
        TbActivityMultimediaExample.Criteria criteria = example.createCriteria();
        criteria.andActivityIdEqualTo(activityId);
        criteria.andIsDeleteEqualTo(Byte.valueOf((byte)0));
        return this.tbActivityMultimediaMapper.selectByExample(example);
    }

    public ActivityDesc getActivityDesc(Integer activityId)
    {
        TbActivityDescExample descExample = new TbActivityDescExample();
        descExample.createCriteria().andActivityIdEqualTo(activityId);
        List<TbActivityDesc> descList = this.tbActivityDescMapper.selectByExample(descExample);
        TbActivityDesc tbActivityDesc = null;
        ActivityDesc activityDesc = new ActivityDesc();
        if (CollectionUtils.isNotEmpty(descList))
        {
            tbActivityDesc = (TbActivityDesc)descList.get(0);
            BeanCopierUtils.copyProperties(tbActivityDesc, activityDesc);
        }
        return activityDesc;
    }

    public List<ActivityInfo> queryActivityList(List<Integer> activityIdList)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Byte.valueOf((byte)0));
        if (CollectionUtils.isNotEmpty(activityIdList)) {
            criteria.andIdIn(activityIdList);
        }
        example.setOrderByClause(" end_time desc");

        List<TbActivity> tbActivityList = this.activityMapper.selectByExample(example);

        List<ActivityInfo> respActivityList = getActivityInfo(tbActivityList);
        return respActivityList;
    }

    public Map<Integer, ActivityInfo> queryActivityMapList(List<Integer> activityIdList)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Byte.valueOf((byte)0)).andStatusEqualTo(Constants.BYTE_ZERO);
        if (CollectionUtils.isNotEmpty(activityIdList)) {
            criteria.andIdIn(activityIdList);
        }
        example.setOrderByClause(" end_time desc");

        List<TbActivity> tbActivityList = this.activityMapper.selectByExample(example);
        if (null == tbActivityList || tbActivityList.size() == 0) {
            return null;
        }
        Map<Integer, ActivityInfo> respActivityMap = new HashMap<Integer, ActivityInfo>();
        for (TbActivity tbActivity : tbActivityList)
        {
            ActivityInfo activityInfo = new ActivityInfo();
            BeanCopierUtils.copyProperties(tbActivity, activityInfo);
            respActivityMap.put(tbActivity.getId(), activityInfo);
        }
        return respActivityMap;
    }

    @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class})
    public Map<Integer, Integer> createWeekActivity(List<Integer> activityIdList, Map<String, Object> condition)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        if (null == condition) {
            return null;
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Byte.valueOf((byte)0));
        if (CollectionUtils.isNotEmpty(activityIdList)) {
            criteria.andIdIn(activityIdList);
        }
        if ((null != condition.get("isWeek")) && (Long)condition.get("isWeek") == 1L)
        {
            Calendar limitDate = Calendar.getInstance(Locale.CHINA);
            Date now = limitDate.getTime();
            limitDate.add(Calendar.DAY_OF_WEEK, -7);
            criteria.andStartTimeBetween(limitDate.getTime(), now);
            criteria.andStatusNotEqualTo(Byte.valueOf((byte)2));
            criteria.andEndTimeLessThanOrEqualTo(now)
            .andIsDeleteEqualTo(Constants.BYTE_ZERO);
            List<TbActivity> list = new ArrayList();
            List<ActivityInfo> result = new ArrayList();
            list = this.activityMapper.selectByExample(example);
            logger.warn("查询符合条件的List结果：" + JSONObject.toJSONString(list));
            if(null == list && list.size() == 0)
            {
                return null;
            }
            Map<Integer, Integer> idMap = new HashMap<Integer, Integer>();
            for (TbActivity activity : list)
            {
                int oldId = activity.getId();
                logger.warn("开始插入一条新的周期活动，活动ID：" + activity.getId());
                activity.setSignStartTime(activity.getEndTime());
                activity.setStartTime(nextWeekDate(activity.getStartTime()));
                activity.setEndTime(nextWeekDate(activity.getEndTime()));
                activity.setSignEndTime(nextWeekDate(activity.getSignEndTime()));
                activity.setAlreadySignTotalNum(0);
                activity.setAlreadyLockSignTotalNum(0);
                activity.setCreateTime(null);
                activity.setUpdateTime(null);
                activity.setId(null);
                int actcount = this.activityMapper.insertSelective(activity);
                if(actcount == 0)
                {
                    throw new RuntimeException("create activity failed, oldActivityId:" + oldId);
                }
                int newId = activity.getId();
                if(newId <= 0)
                {
                     continue;
                }
                TbActivityDescExample descExample = new TbActivityDescExample();
                descExample.createCriteria().andActivityIdEqualTo(oldId);
                List<TbActivityDesc> descs = tbActivityDescMapper.selectByExample(descExample);
                if(null == descs || descs.size() == 0)
                {
                    continue;
                }
                TbActivityDesc tbActivityDesc = descs.get(0);
                tbActivityDesc.setActivityId(newId);
                tbActivityDesc.setCreateTime(null);
                tbActivityDesc.setUpdateTime(null);
                int desCount = this.tbActivityDescMapper.insertSelective(tbActivityDesc);
                if(desCount == 0)
                {
                    throw new RuntimeException("create activityDesc failed, oldActivityId:" + oldId);
                }
                idMap.put(oldId, newId);
                TbActivityMultimediaExample multimediaExample = new TbActivityMultimediaExample();
                multimediaExample.createCriteria().andActivityIdEqualTo(oldId)
                        .andIsDeleteEqualTo(Constants.BYTE_ZERO);
                List<TbActivityMultimedia> multimedias =
                        tbActivityMultimediaMapper.selectByExample(multimediaExample);
                if(null == multimedias || multimedias.size() == 0)
                {
                    continue;
                }
                else {
                    for (TbActivityMultimedia activityMedia : multimedias)
                    {
                        activityMedia.setCreateTime(null);
                        activityMedia.setUpdateTime(null);
                        activityMedia.setActivityId(newId);
                    }
                    int mulcount = activityMultimediaMapper.batchInsert(multimedias);
                    if(mulcount == 0)
                    {
                        throw new RuntimeException("create multimedia failed, oldActivityId:" + oldId);
                    }
                }
            }
            return idMap;
        }
        return null;
    }

    public List<ActivityInfo> queryActivityListByCondition(List<Integer> activityIdList, Map<String, Object> condition)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        if (null == condition) {
            return queryActivityList(activityIdList);
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        if (CollectionUtils.isNotEmpty(activityIdList)) {
            criteria.andIdIn(activityIdList);
        }
        if (null != condition.get("isSign"))
        {
            Long isSign = (Long)condition.get("isSign");
            if (isSign == 1L)
            {
                Date now = new Date();
                //criteria.andSignStartTimeLessThanOrEqualTo(now);暂时没参考意义
                criteria.andSignEndTimeGreaterThanOrEqualTo(now);
            }
        }
        example.setOrderByClause(" id desc");
        List<TbActivity> tbActivityList = this.activityMapper.selectByExample(example);

        List<ActivityInfo> respActivityList = getActivityInfo(tbActivityList);
        return respActivityList;
    }

    public List<Integer> queryActivityIdsByCondition(List<Integer> activityIdList, Map<String, Object> condition)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            return null;
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO).andIdIn(activityIdList);
        //检索给定的IDLIST中还未开始的活动并返回
        if (null != condition.get("placeId"))
        {
            Integer placeId = (Integer)condition.get("placeId");
            criteria.andPlaceIdEqualTo(placeId);
        }
        if (null != condition.get("isNotStart"))
        {
            Long isNotStart = (Long)condition.get("isNotStart");
            if (isNotStart == 1L)
            {
                Date now = new Date();
                //criteria.andSignStartTimeLessThanOrEqualTo(now);暂时没参考意义
                criteria.andStatusEqualTo((byte)0);
                //criteria.andStartTimeGreaterThan(now);11.15产品要求改为未结束的
                criteria.andEndTimeGreaterThan(now);
            }
            example.setOrderByClause(" start_time asc");
        }
        //检索给定的IDLIST中进行中的活动并返回
        if (null != condition.get("isStart"))
        {
            Long isStart = (Long)condition.get("isStart");
            if (isStart == 1L)
            {
                Date now = new Date();
                criteria.andStatusEqualTo((byte)0);
                criteria.andStartTimeLessThanOrEqualTo(now);
                criteria.andEndTimeGreaterThan(now);
            }
        }
        //检索给定的IDLIST中已经结束的活动并返回
        if (null != condition.get("isEnd"))
        {
            Long isEnd = (Long)condition.get("isEnd");
            if (isEnd == 1L)
            {
                Date now = new Date();
                criteria.andStatusNotEqualTo(Constants.BYTE_TWO);
                criteria.andEndTimeLessThanOrEqualTo(now);
            }
        }
        //检索给定的IDLIST中本周内开始的有效活动
        if (null != condition.get("taskWeek"))
        {
            Long taskWeek = (Long)condition.get("taskWeek");
            if (taskWeek == 1L)
            {
                Date now = new Date();
                criteria.andStatusEqualTo((byte)0);
                logger.warn("startTime-endTime:" + DateUtils.getTimesWeekmorning(new Date()) + "" +
                        DateUtils.getTimesWeeknight(new Date()));
                criteria.andStartTimeBetween(DateUtils.getTimesWeekmorning(new Date()),
                        DateUtils.getTimesWeeknight(new Date()));
            }
        }

        //检索给定的IDLIST中规定时间内开始的有效活动
        if (null != condition.get("start")&&null == condition.get("end"))
        {
            Date taskStart = (Date) condition.get("start");
            criteria.andStatusEqualTo((byte)0);
            logger.warn("startTime-null:" + taskStart + "");
            criteria.andStartTimeGreaterThan(taskStart);
        }else if(null != condition.get("start")&&null != condition.get("end")){
            Date taskStart = (Date)condition.get("start");
            Date taskEnd = (Date)condition.get("end");
            criteria.andStatusEqualTo((byte)0);
            logger.warn("startTime-endTime:" + taskStart + ""+ taskEnd + "");
            criteria.andStartTimeBetween(taskStart,taskEnd);
        }
        //检索给定的IDLIST中本月内开始的有效活动
        if (null != condition.get("taskMonth"))
        {
            Long taskMonth = (Long)condition.get("taskMonth");
            if (taskMonth == 1L)
            {
                Date now = new Date();
                criteria.andStatusEqualTo((byte)0);
                criteria.andStartTimeBetween(DateUtils.getTimesMonthmorning(),
                        DateUtils.getTimesMonthnight());
            }
        }
        //检索给定的IDLIST中一天内开始的有效活动
        if (null != condition.get("taskDay"))
        {
            Long taskMonth = (Long)condition.get("taskDay");
            if (taskMonth == 1L)
            {
                Date now = new Date();
                criteria.andStatusEqualTo((byte)0);
                criteria.andStartTimeBetween(DateUtils.getTimesmorning(),
                        DateUtils.getTimesnight());
            }
        }
        List<TbActivity> list = activityMapper.selectByExample(example);
        if(null == list || list.size() == 0)
        {
            return null;
        }
        List<Integer> resultIds = new ArrayList<Integer>();
        for(TbActivity activity: list)
        {
            resultIds.add(activity.getId());
        }
        return resultIds;
    }

    @Override
    public List<List<Integer>> queryEveryDayActivityByCondition(List<List<Integer>> activityIdList, Map<String, Object> condition) {

        if (CollectionUtils.isEmpty(activityIdList)) {
            return null;
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO).andIdIn(activityIdList.get(0));
        //检索给定的IDLIST中规定时间内开始的有效活动
        if (null != condition.get("start")&&null == condition.get("end"))
        {
            Date taskStart = (Date) condition.get("start");
            criteria.andStatusNotEqualTo((byte)2);
            logger.warn("startTime-null:" + taskStart + "");
            criteria.andStartTimeGreaterThan(taskStart);
        }else if(null != condition.get("start")&&null != condition.get("end")){
            Date taskStart = (Date)condition.get("start");
            Date taskEnd = (Date)condition.get("end");
            criteria.andStatusNotEqualTo((byte)2);
            logger.warn("startTime-endTime:" + taskStart + ""+ taskEnd + "");
            criteria.andStartTimeBetween(taskStart,taskEnd);
        }
        List<TbActivity> list = activityMapper.selectByExample(example);
        if(null == list || list.size() == 0)
        {
            return null;
        }
        List<List<Integer>> resultEveryDayIds = new ArrayList<>();
        List<Integer> resultIds = new ArrayList<Integer>();
        for(TbActivity activity: list)
        {
            resultIds.add(activity.getId());
        }
        resultEveryDayIds.add(resultIds);
        return resultEveryDayIds;
    }

    public ActivityInfo selectSignActivityByUid(List<Integer> activityIdList, Map<String, Object> condition)
    {
        if(null == activityIdList)
        {
            logger.warn("activityIdList 为空");
            return null;
        }
        Integer activityId = null;
        List<Integer> ids = queryActivityIdsByCondition(activityIdList, condition);
        //获取时间离现在最近的活动ID
        if(null != ids && ids.size() > 0)
        {
            activityId = ids.get(0);
            return queryOneActivityById(activityId);
        }
        return null;
    }

    public int countActivityListByCondition(List<Integer> activityIdList, Map<String, Object> condition)
    {
        if (CollectionUtils.isEmpty(activityIdList)) {
            APIResponse.returnSuccess("没有更多的活动!");
        }
        if (null == condition) {
            return 0;
        }
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(Constants.BYTE_ZERO);
        if (CollectionUtils.isNotEmpty(activityIdList)) {
            criteria.andIdIn(activityIdList);
        }
        if (null != condition.get("isSign"))
        {
            Long isSign = (Long)condition.get("isSign");
            if (isSign.longValue() == 1L)
            {
                Date now = new Date();
                criteria.andStatusEqualTo(Constants.BYTE_ZERO);
                criteria.andSignEndTimeGreaterThan(now);
            }
        }
        int total = this.activityMapper.countByExample(example);
        return total;
    }

    private static Date nextWeekDate(Date date)
    {
        Calendar newDate = Calendar.getInstance(Locale.CHINA);
        newDate.setTime(date);
        newDate.add(Calendar.DATE, 7);
        return newDate.getTime();
    }

    public List<ActivityInfo> getActivityInfo(List<TbActivity> tbActivityList)
    {
        List<ActivityInfo> respActivityList = new ArrayList();
        if (CollectionUtils.isNotEmpty(tbActivityList)) {
            for (TbActivity tbActivity : tbActivityList)
            {
                ActivityInfo activityInfo = new ActivityInfo();
                BeanCopierUtils.copyProperties(tbActivity, activityInfo);
                respActivityList.add(activityInfo);
            }
        }
        return respActivityList;
    }

    public List<ActivityInfo> getActivityExtendInfo(List<TbActivityDesc> descList, List<TbActivityMultimedia> tbActivityMultimediaList, List<TbActivity> tbActivityList)
    {
        List<ActivityInfo> respActivityList = new ArrayList();
        if (CollectionUtils.isNotEmpty(tbActivityList)) {
            for (TbActivity tbActivity : tbActivityList)
            {
                ActivityInfo activityInfo = new ActivityInfo();
                BeanCopierUtils.copyProperties(tbActivity, activityInfo);

                setActivityByMedia(tbActivityMultimediaList, activityInfo, tbActivity);

                setActivityByDesc(descList, activityInfo, tbActivity);
                respActivityList.add(activityInfo);
            }
        }
        return respActivityList;
    }

    public void setActivityByDesc(List<TbActivityDesc> descList, ActivityInfo activityInfo, TbActivity tbActivity)
    {
        if (CollectionUtils.isNotEmpty(descList))
        {
            ActivityDesc activityDesc = null;
            for (TbActivityDesc tbActivityDesc : descList) {
                if (tbActivityDesc.getActivityId() == tbActivity.getId())
                {
                    activityDesc = new ActivityDesc();
                    BeanCopierUtils.copyProperties(tbActivityDesc, activityDesc);
                }
            }
            activityInfo.setActivityDesc(activityDesc);
        }
    }

    public void setActivityByMedia(List<TbActivityMultimedia> tbActivityMultimediaList, ActivityInfo activityInfo, TbActivity tbActivity)
    {
        List<ActivityMedia> activityMediaList = new ArrayList();
        if (CollectionUtils.isNotEmpty(tbActivityMultimediaList))
        {
            for (TbActivityMultimedia tbActivityMultimedia : tbActivityMultimediaList) {
                if (tbActivityMultimedia.getActivityId().equals(tbActivity.getId()))
                {
                    ActivityMedia activityMedia = new ActivityMedia();
                    BeanCopierUtils.copyProperties(tbActivityMultimedia, activityMedia);
                    activityMediaList.add(activityMedia);
                }
            }
            activityInfo.setActivityMediaList(activityMediaList);
        }
    }

    public boolean collectActivity(Integer uid, Integer activityId, Integer type)
    {
        ReqUserCollect reqUserCollect = new ReqUserCollect();
        reqUserCollect.setSystemCode("ACTIVITY_SYSTEM_CODE");
        reqUserCollect.setBusinessCode("CLUB_COLLECT_ACTIVITY_BUSINESS_CODE");
        reqUserCollect.setUserId(uid);
        reqUserCollect.setBusinessId(activityId);
        reqUserCollect.setStatus(type);
        APIRequest apiRequest = new APIRequest();
        if (type.intValue() == 1) {
            apiRequest.setServicesName("userCollect");
        } else {
            apiRequest.setServicesName("cancleUserCollect");
        }
        apiRequest.setRequestData(reqUserCollect);

        APIResponse<?> apiResponse = null;
        if (!apiResponse.isRet()) {
            return false;
        }
        APIResponse<Integer> response = new APIResponse();
        BeanCopierUtils.copyProperties(apiResponse, response);
        if (apiResponse.getErrcode() == ApiResponseEnum.SUCCESS.getId()) {
            response.setData(Integer.valueOf(1));
        } else {
            return false;
        }
        return true;
    }

    public PageObj<List<ActivityInfo>> myActivityList(Integer uid, Integer pageSize, Integer pageIndex)
    {
        int total = this.queryMyActivityMapper.countMyActivityList(uid, pageSize, pageIndex);
        List<TbActivity> activityList = this.queryMyActivityMapper.myActivityList(uid, pageSize, pageIndex);
        List<ActivityInfo> activityInfoList = getActivityInfo(activityList);
        PageObj<List<ActivityInfo>> pageObj = PageObj.create(total, pageIndex.intValue(), pageSize.intValue(), activityInfoList);
        return pageObj;
    }

    public PageObj<List<ActivityInfo>> queryOneActivityByPlaceId(Integer placeId, Integer pageNum, Integer pageSize)
    {
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId).andSignEndTimeGreaterThan(new Date()).andStatusNotEqualTo((byte)2);
        example.setOrderByClause(" start_time asc ");
        int count = this.activityMapper.countByExample(example);
        if (count > 0) {
            example.setLimit(Limit.buildLimit(pageNum.intValue(), pageSize.intValue()));
        }
        List<TbActivity> tbActivityList = this.activityMapper.selectByExample(example);
        List<ActivityInfo> activityInfoList = new ArrayList();
        if (CollectionUtils.isNotEmpty(tbActivityList)) {
            for (TbActivity tbActivity : tbActivityList) {
                if(null == tbActivity.getLimitNum())
                {
                    continue;
                }
                if(tbActivity.getLimitNum().intValue()
                        < tbActivity.getAlreadySignTotalNum().intValue() &&
                        tbActivity.getLimitNum().intValue() != 0)
                {
                    continue;
                }
                ActivityInfo activityInfo = new ActivityInfo();
                BeanCopierUtils.copyProperties(tbActivity, activityInfo);
                activityInfo.setGroupId(tbActivity.getGroupId());
                activityInfoList.add(activityInfo);
            }
        }
        PageObj<List<ActivityInfo>> pageObj = PageObj.create(count, pageNum.intValue(), pageSize.intValue(), activityInfoList);
        return pageObj;
    }

    public PageObj<List<ActivityInfo>> queryOneActivityByPlaceId(Integer placeId, Integer categoryId, Integer pageNum, Integer pageSize)
    {
        TbActivityExample example = new TbActivityExample();
        TbActivityExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceIdEqualTo(placeId)
                .andSignEndTimeGreaterThan(new Date())
                .andStatusNotEqualTo((byte)2)
                .andCategoryIdEqualTo(categoryId);
        example.setOrderByClause(" start_time asc ");
        int count = this.activityMapper.countByExample(example);
        if (count > 0) {
            example.setLimit(Limit.buildLimit(pageNum.intValue(), pageSize.intValue()));
        }
        List<TbActivity> tbActivityList = this.activityMapper.selectByExample(example);
        List<ActivityInfo> activityInfoList = new ArrayList();
        if (CollectionUtils.isNotEmpty(tbActivityList)) {
            for (TbActivity tbActivity : tbActivityList) {
                if(null == tbActivity.getLimitNum())
                {
                    continue;
                }
                if(tbActivity.getLimitNum().intValue()
                        < tbActivity.getAlreadySignTotalNum().intValue() &&
                        tbActivity.getLimitNum().intValue() != 0)
                {
                    continue;
                }
                ActivityInfo activityInfo = new ActivityInfo();
                BeanCopierUtils.copyProperties(tbActivity, activityInfo);
                activityInfo.setGroupId(tbActivity.getGroupId());
                activityInfoList.add(activityInfo);
            }
        }
        PageObj<List<ActivityInfo>> pageObj = PageObj.create(count, pageNum.intValue(), pageSize.intValue(), activityInfoList);
        return pageObj;
    }

    public PageObj<List<ActivityInfo>> queryDeleteActivity(Integer pageNum, Integer pageSize)
    {
        TbActivityExample example = new TbActivityExample();
        example.createCriteria().andIsDeleteEqualTo((byte)1);
        Integer total = activityMapper.countByExample(example);
        if(total == 0)
        {
            return null;
        }
        example.setLimit(Limit.buildLimit(pageNum, pageSize));
        example.setOrderByClause(" create_time desc");
        List<TbActivity> list = activityMapper.selectByExample(example);
        List<ActivityInfo> result = new ArrayList<ActivityInfo>();
        for(TbActivity tbActivity : list)
        {
            ActivityInfo info = new ActivityInfo();
            info.setId(tbActivity.getId());
            info.setName(tbActivity.getName());
            info.setCategoryId(tbActivity.getCategoryId());
            info.setStartTime(tbActivity.getStartTime());
            info.setEndTime(tbActivity.getEndTime());
            info.setSignStartTime(tbActivity.getSignStartTime());
            info.setSignEndTime(tbActivity.getSignEndTime());
            info.setStatus(tbActivity.getStatus());
            result.add(info);
        }
        return PageObj.create(total, pageNum, pageSize, result);
    }

    public Map<Long, Long> queryIsFull(List<Integer> activityIds)
    {
        if(null == activityIds || activityIds.size() == 0)
        {
            return null;
        }
        List<Map<String, Long>> maps = queryMyActivityMapper.selectIsFull(activityIds);
        Map<Long, Long> result = new HashMap<Long, Long>();
        for(Map<String, Long> map : maps)
        {
            result.put(map.get("id"), map.get("isFull"));
        }
        return result;
    }

    @Override
    public List<Integer> queryActivityIdsByName(String activityName) {

        List<Integer> ids = new ArrayList<>();
        TbActivityExample example = new TbActivityExample();
        example.createCriteria().andNameLike(activityName+"%");
        List<TbActivity> list = activityMapper.selectByExample(example);
        for (TbActivity activity : list){
            ids.add(activity.getId());
        }
        return ids;
    }
}
